<?php
class MemberController extends Zend_Controller_Action
{
	private $_uiVar = array();
	private $_member;
	private $_privilege;

	public function init()
	{
		$this->_uiVar["html"]["title"] = BMSC_Html::WEBSITE_TITLE;

		try
		{
			$readerDb = Zend_Registry::get("READER_DB");
			$writerDb = Zend_Registry::get("WRITER_DB");

			$this->_member = new BMSC_Member($readerDb, $writerDb);
			$this->_privilege = new BMSC_Privilege($readerDb, $writerDb);
		}
		catch (Exception $ex)
		{
			echo $ex->getMessage();
		}
	}
	
	public function checkAdminAction()
	{
		try {
			$isAdmin = $this->_isLoggedUserAdmin();
			echo json_encode(array('isAdmin' => $isAdmin));
		} catch(Exception $e) {
			
		}
	}
	
	function removeAction()
	{
		$adminSession = new Zend_Session_Namespace("BMSC_ADMIN");
		if ((isset($adminSession->member["IS_LOGIN"])) && ($adminSession->member["IS_LOGIN"] == 1))
		{
			try
			{
				$formData = $_POST;
				$formData = $this->_trimRemoveMemberData($formData);
				$errorMessage = $this->_checkRemoveMemberData($formData);
				if (empty($errorMessage))
				{
					// check if the removed user is the logged-in user
					$isMyself = $formData['removeMemberID'] == $adminSession->member['ID'] ? 1 : 0;
					
					$row = $this->_member->removeMember($formData["removeMemberID"]);
					if ($row > 0)
						echo json_encode(array("code" => 0, 'isMyself' => $isMyself, "data" => "- Thành công. <br />"));
					else
						echo json_encode(array("code" => -98, "data" => "- Có lỗi khi lưu dữ liệu vào cơ sở dữ liệu. <br />"));
				}
				else
					echo json_encode(array("code" => -99, "data" => $errorMessage));
			}
			catch (Exception $ex)
			{
				echo json_encode(array("code" => -101, "data" => $ex->getMessage()));
			}
		}
		else
			echo json_encode(array("code" => -100, "data" => "- Bạn cần phải đăng nhập để thực hiện chức năng này. <br />"));
	}
	
	public function editAction()
	{
		$adminSession = new Zend_Session_Namespace("BMSC_ADMIN");
		if ((isset($adminSession->member["IS_LOGIN"])) && ($adminSession->member["IS_LOGIN"] == 1))
		{
			try
			{
				$formData = $_POST;
				$formData = $this->_trimEditMemberData($formData);
				$errorMessage = $this->_checkEditMemberData($formData);
				if (empty($errorMessage))
				{	
					// check if the edited user is the logged-in user
					$isMyself = $formData['editMemberID'] == $adminSession->member['ID'] ? 1 : 0;
					
					// isAdmin is used for checking if the logged-in user is admin
					$isAdmin = $this->_getParam('isAdmin');
					if($isAdmin) {
						$row = $this->_member->editMember(
						$formData["editMemberID"], 
						$formData["editMemberFullName"], 
						$formData["editMemberEmail"], 
						$formData["editMemberNewPassword"],
						isset($formData["editMemberIsAdmin"]) ? 1 : 0, 
						isset($formData["editMemberIsActive"]) ? 1 : 0,
						isset($formData["editMemberPasswordBool"]) ? 1 : 0
						);
						
						// if edited user is logged user.
						if($isMyself) {
							$isAdmin = $adminSession->member['IS_ADMIN'] = isset($formData['editMemberIsAdmin']) ? 1 : 0;
						}
					} else {
						$row = $this->_member->editMyself(
						$formData["editMemberID"], 
						$formData["editMemberFullName"], 
						$formData["editMemberEmail"], 
						$formData["editMemberNewPassword"],
						isset($formData["editMemberPasswordBool"]) ? 1 : 0
						);
					}
					
					echo json_encode(array("code" => 0, 'isAdmin' => $isAdmin, 'isMyself' => $isMyself, "data" => "- Thành công. <br />"));
				}
				else
					echo json_encode(array("code" => -99, "data" => $errorMessage));
			}
			catch (Exception $ex)
			{
				echo json_encode(array("code" => -101, "data" => $ex->getMessage()));
			}
		}
		else
			echo json_encode(array("code" => -100, "data" => "- Bạn cần phải đăng nhập để thực hiện chức năng này. <br />"));
	}
	
	public function getInfoAction()
	{
		$adminSession = new Zend_Session_Namespace("BMSC_ADMIN");
		if ((isset($adminSession->member["IS_LOGIN"])) && ($adminSession->member["IS_LOGIN"] == 1))
		{
			try
			{
				$memberID = (int)trim($this->_getParam("id"));
				$member = $this->_member->getMember($memberID);
				echo json_encode(array("code" => 0, 									    
									   "data" => $member));
			}
			catch (Exception $ex)
			{
				echo json_encode(array("code" => -101, "data" => $ex->getMessage()));
			}
		}
		else
			echo json_encode(array("code" => -100, "data" => "- Bạn cần phải đăng nhập để thực hiện chức năng này. <br />"));
	}
	
	public function addAction()
	{
		$adminSession = new Zend_Session_Namespace("BMSC_ADMIN");
		if ((isset($adminSession->member["IS_LOGIN"])) && ($adminSession->member["IS_LOGIN"] == 1))
		{
			try
			{
				$formData = $_POST;
				$formData = $this->_trimNewMemberData($formData);
				$errorMessage = $this->_checkNewMemberData($formData);
				if (empty($errorMessage))
				{					
					$row = $this->_member->addMember(
					$formData["newMemberFullName"], 
					$formData["newMemberEmail"], 
					$formData["newMemberPassword"], 
					isset($formData['newMemberIsAdmin']) ? 1 : 0, 
					isset($formData['newMemberIsActive']) ? 1 : 0
					);
					if ($row > 0)
						echo json_encode(array("code" => 0, "data" => "- Thành công. <br />"));
					else
						echo json_encode(array("code" => -98, "data" => "- Có lỗi khi lưu dữ liệu vào cơ sở dữ liệu. <br />"));
				}
				else
					echo json_encode(array("code" => -99, "data" => $errorMessage));
			}
			catch (Exception $ex)
			{
				echo json_encode(array("code" => -101, "data" => $ex->getMessage()));
			}
		}
		else
			echo json_encode(array("code" => -100, "data" => "- Bạn cần phải đăng nhập để thực hiện chức năng này. <br />"));
	}
	
	public function listAction()
	{
		$adminSession = new Zend_Session_Namespace("BMSC_ADMIN");
		if ((isset($adminSession->member["IS_LOGIN"])) && ($adminSession->member["IS_LOGIN"] == 1))
		{
			try
			{
				$isAdmin = $this->_getParam("isAdmin");				
				if($isAdmin) {
					$from = (int)trim($this->_getParam("from"));
					$numberOfMembers = (int)trim($this->_getParam("number"));
					$members = $this->_member->getMemberList($from, $numberOfMembers);
				} else {
					$members = $this->_member->getMyself($adminSession->member["ID"]);
				}
				echo json_encode(array("code" => 0, "data" => $members));
			}
			catch (Exception $ex) {
				echo json_encode(array("code" => -101, "data" => $ex->getMessage()));
			}
		}
		else
			echo json_encode(array("code" => -100, "data" => "- Bạn cần phải đăng nhập để thực hiện chức năng này. <br />"));
	}
	
	function indexAction()
	{
		$adminSession = new Zend_Session_Namespace("BMSC_ADMIN");
		if ((isset($adminSession->member["IS_LOGIN"])) && ($adminSession->member["IS_LOGIN"] == 1))
		{			
			$smarty = Zend_Registry::get("SMARTY");
			$smarty->assign("uiVar", $this->_uiVar);			
			$smarty->display("member/index.tpl");
		}
		else
		{
			$zokikAdminSession->redirect["NEXT_URL"] = "/member";
			header("Location: /member/login");
		}
	}

	function loginAction()
	{	
		$adminSession = new Zend_Session_Namespace("BMSC_ADMIN");
		if ((!isset($adminSession->member["isLogin"])) || ($adminSession->member["isLogin"] == 0))
		{
			if ($this->getRequest()->isPost())
			{
				$formData = $_POST;
				$formData = $this->_trimLoginData($formData);
				
				$errorMessage = $this->_checkLoginData($formData);
				if (empty($errorMessage))
				{
					
					$member = $this->_member->checkLogin($formData["email"], $formData["password"]);
					if ($member !== false)
					{
						$adminSession->member["ID"] = $member["ID"];
						$adminSession->member["FULLNAME"] = $member["FULLNAME"];
						$adminSession->member["EMAIL"] = $member["EMAIL"];						
						$adminSession->member["IS_LOGIN"] = 1;
						
						$row = $this->_member->checkAdmin($member["ID"]);
						$adminSession->member["IS_ADMIN"] = !empty($row) ? 1 : 0;
						
						/////////// page privilege operation //////////////
						// $pagePrivileges = $this->_privilege->getPagePrivileges($adminSession->member['ID']);
						// if(!empty($pagePrivileges)) {	
							// $adminSession->member['pagePrivileges'] = $pagePrivileges;
						// } else {
							// $adminSession->member['pagePrivileges'] = array();
						// }
						

						$returnData["code"] = 0;
						$returnData["data"] = "";
						echo json_encode($returnData);
					}
					else
					{
						$returnData["code"] = -98;
						$returnData["data"] = "- Thông tin đăng nhập không hợp lệ, vui lòng kiểm tra lại. <br />";
						echo json_encode($returnData);
					}
				}
				else
				{					
					$returnData["code"] = -99;
					$returnData["data"] = $errorMessage;
					echo json_encode($returnData);
				}
			}
			else
			{
				$smarty = Zend_Registry::get("SMARTY");
				$smarty->assign("uiVar", $this->_uiVar);
				$smarty->display("member/login.tpl");
			}
		}
		else
		{
			if ((isset($adminSession->redirect["NEXT_URL"])) && (!empty($adminSession->redirect["NEXT_URL"])))
				header("Location: " . $adminSession->redirect["NEXT_URL"]);
			else
				header("Location: /overview");
		}
	}

	function logoutAction()
	{
		$adminSession = new Zend_Session_Namespace("BMSC_ADMIN");
		$adminSession->member = array();
		header("Location: /");
	}
	
	private function _isLoggedUserAdmin()
	{
		$adminSession = new Zend_Session_Namespace("BMSC_ADMIN");
		$r = $this->_member->checkAdmin($adminSession->member['ID']);
		return !empty($r) ? 1 : 0;		
	}
	
	private function _checkNewMemberData($formData)
	{
		if (empty($formData["newMemberFullName"]) || empty($formData["newMemberEmail"]) ||
			empty($formData["newMemberPassword"]) || empty($formData["newMemberPasswordConfirm"]))
			return "- Vui lòng nhập vào các thông tin bắt buộc. <br />";
		if($formData['newMemberPassword'] != $formData['newMemberPasswordConfirm'])
			return "- Mật khẩu không trùng khớp. <br />";
	}
	
	private function _checkEditMemberData($formData)
	{
		// fullname and email validation
		if (empty($formData["editMemberFullName"]) || empty($formData["editMemberEmail"])) {		
			return "- Vui lòng nhập vào các thông tin bắt buộc. <br />";
		}
		
		$isAdmin = $this->_isLoggedUserAdmin();
		// password validation
		if(!$isAdmin) { // is not admin
			if(isset($formData['editMemberPasswordBool'])) { // check if password checkbox is checked
				if(empty($formData['editMemberCurrentPassword']) || 
				   empty($formData['editMemberNewPassword']) ||
				   empty($formData['editMemberNewPasswordConfirm'])) { // check if any of these is empty
					return "- Vui lòng nhập vào các thông tin bắt buộc. <br />";
				}
			}
		} else { // is admin
				if(isset($formData['editMemberPasswordBool']) &&
				   (empty($formData['editMemberNewPassword']) ||
				    empty($formData['editMemberNewPasswordConfirm']))) { // check if any of these is empty
					return "- Vui lòng nhập vào các thông tin bắt buộc. <br />";					
				}
		}
		
		// check if new password and new password confirm are matched	
		if(isset($formData['editMemberPasswordBool']) &&
		   ($formData['editMemberNewPassword'] != $formData['editMemberNewPasswordConfirm'])){
			return "- Mật khẩu không trùng khớp. <br />";
		}
		
		// (IMPORTANT PART)
		// check if current password is right and if it is different to the old one
		if(isset($formData['editMemberPasswordBool']) && $isAdmin == 0) {
			$member = $this->_member->checkLogin($formData['editMemberEmail'], 
												 $formData['editMemberCurrentPassword']);	
			if(empty($member)) {				
				return '- Mật khẩu hiện hành sai.';
			}			
			if($member["PASSWORD"] == md5($formData['editMemberNewPassword'])) {
				return "- Mật khẩu mới phải khác mật khẩu cũ";
			}
		}
		
		return "";
	}
	
	private function _trimNewMemberData($formData)
	{
		$formData["newMemberFullName"] = trim($formData["newMemberFullName"]);
		$formData["newMemberEmail"] = trim($formData["newMemberEmail"]);
		return $formData;
	}
	
	private function _trimEditMemberData($formData)
	{
		$formData["editMemberFullName"] = trim($formData["editMemberFullName"]);
		$formData["editMemberEmail"] = trim($formData["editMemberEmail"]);
		return $formData;
	}
	
	private function _trimLoginData($formData)
	{
		$formData["email"] = trim($formData["email"]);
		return $formData;
	}

	private function _checkLoginData($formData)
	{
		$errorMessage = "";

		if (empty($formData["email"]) || empty($formData["password"]))
			$errorMessage = "- Vui lòng nhập vào các thông tin bắt buộc. <br />";

		return $errorMessage;
	}
	
	private function _trimRemoveMemberData($formData)
	{
		$formData["removeMemberID"] = trim($formData["removeMemberID"]);
		return $formData;
	}
	
	private function _checkRemoveMemberData($formData)
	{
		$errorMessage = "";
		if (empty($formData["removeMemberID"]))
			$errorMessage = "- Vui lòng nhập vào các thông tin bắt buộc. <br />";
		return $errorMessage;
	}
}
?>